#!/usr/bin/env python
# $Id: rdate.py 7eaaa50bb501 2013/07/17 05:34:21 pgurumur $
# Copyright (c) 2013 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# File rdate.py generated on Friday June 07, 2013 @23:08:19 PDT
#
__version__  = "$Revision: 7eaaa50bb501 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2013-07-17 05:34:21Z $"

import os
import optparse
import sys

from venya.lib import cmdparser
from venya.lib import exception
from venya.lib import stdlib

class rdate(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-4", "--ipv4", action = "store_true",
            help = "Use IPv4 for communication", default = False, dest = "v4"),
         optparse.make_option("-6", "--ipv6", action = "store_true",
            help = "Use IPv6 for communication", default = False, dest = "v6"),
         optparse.make_option("-p", "--port",  type = "int",
            help = "NTP/Time port to use", default = 0, dest = "port"),
         optparse.make_option("-c", "--correct", action = "store_true",
            help = "Correct leap second count", default = False,
            dest = "correct"),
         optparse.make_option("-s", "--sntp", action = "store_true",
            help = "Use SNTP instead of RFC 868 time protocol", default = False,
            dest = "sntp"),
   ) + cmdparser.GetOpt.option_list

   help = """

   Not written yet!"
   """

   usage = "[ timeservers ]"

   def __init__(self, **Keywords):
      super(stdlib.my_class(self), self).__init__(**Keywords)
      self._family = None
      self._port = 0
      self._sock = None

   def frac2bin(self, value):
      binary = ""
      while (len(binary) < 32):
         temp = value * 2
         binary += "%d" %int(temp)
         value = temp - int(temp)

      return binary

   def sockconn(self, host):
      sockList = []
      try:
         sockList = socket.getaddrinfo(host, self._port, self._family,
               socket.SOCK_DGRAM, socket.IPPROTO_UDP)
      except socket.gaierror as err:
         self.error("getaddrinfo: errno %d, message: %s", err.args[0],
               err.args[1])

      mesg = None
      for res in sockList:
         af, socktype, proto, canonname, sa = res
         try:
            self._sock = socket.socket(af, socktype, proto)
         except socket.error:
            self._sock = None

         try:
            self._sock.connect(sa)
         except socket.error as err:
            mesg = err.args[1]
            self._sock.close()
            self._sock = None
            continue

      if self._sock is None:
         self.error(mesg)

   def ntpclient(self, hosts = []):
      jan1970 = 2208988800.00
      ntpscale = pow(2, 32)
      # 11 100 011 1111 0100 1000
      # E3 F
      leap = 3
      version = 4
      mode = 3
      stratum = 16

      maxdelay = 15

      for host in hosts:
         localtime = time.time() + jan1970
         self.sockconn(host)


   def rfc868client(self, hosts = []):
      pass

   @cmdparser.getopts
   def handle(self):
      if self.options.v4 and self.options.v6:
         self.error("choose either IPv4 or IPv6, not both")

      hosts = []
      try:
         hosts = self.arguments[1:]
      except IndexError:
         self.error("Need timeserver to query")

      if self.options.v4:
         self._family = socket.AF_INET
      elif self.options.v6:
         self._family = socket.AF_INET6

      if self.options.sntp:
         self._port = 123
         self.ntpclient(hosts)
      else:
         self.rfc868client(hosts)

if __name__ == "__main__":
   client = None
   try:
      client = rdate(version = 0.1, args = sys.argv)
      if client.length <= 1:
         client.printhelp()
      else:
         client.handle()
   except exception.GetOptError as err:
      print(err)
      sys.exit(1)
